/**
 * PrivilegeTag.java
 */
package org.yate.oa.controller.tags;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.yate.oa.model.LoginEntity;
import org.yate.oa.model.PrivilegeEntity;
import org.yate.oa.service.IPrivilegeService;
import org.yate.oa.utils.Constants;

/**
 * @author Yate
 * @date Nov 21, 2013
 * @description TODO
 * @version 1.0
 */
public class PrivilegeTag extends TagSupport {
	protected ServletContext context;
	protected ApplicationContext springCtx;
	protected IPrivilegeService ps;
	protected HttpServletRequest req;

	protected Long privId;

	/**
	 * @return the privId
	 */
	public final Long getPrivId() {
		return privId;
	}

	/**
	 * @param privId
	 *            the privId to set
	 */
	public final void setPrivId(Long privId) {
		this.privId = privId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.jsp.tagext.TagSupport#setPageContext(javax.servlet.jsp.
	 * PageContext)
	 */
	@Override
	public void setPageContext(PageContext pageContext) {
		super.setPageContext(pageContext);
		this.context = pageContext.getServletContext();
		this.springCtx = WebApplicationContextUtils
				.getWebApplicationContext(this.context);
		this.ps = (IPrivilegeService) this.springCtx
				.getBean("privilegeService");
		this.req = (HttpServletRequest) this.pageContext.getRequest();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
	 */
	@Override
	public int doStartTag() throws JspException {
		LoginEntity u = (LoginEntity) req.getSession().getAttribute(
				Constants.SESSION_USER_ENTITY);
		if (u == null) {
			return SKIP_BODY;
		}
		PrivilegeEntity p = ps.getEntityByUIDAndPID(u.getUserId(), this.privId);
		return p == null ? SKIP_BODY : EVAL_BODY_INCLUDE;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.jsp.tagext.TagSupport#release()
	 */
	@Override
	public void release() {
		super.release();
		this.springCtx = null;
		this.context = null;
		this.ps = null;
		this.req = null;
	}

}
